package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"short-video-dev/cache"
	"short-video-dev/pkg"
	"strconv"
	"time"

	"short-video-dev/videorpc/internal/svc"
	"short-video-dev/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 验证码发送
func (l *SendSmsLogic) SendSms(in *videorpc.SendSmsRequest) (*videorpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	code := rand.Intn(9000) + 1000
	smsKey := fmt.Sprintf("sms_%v", in.Mobile)
	sms, _ := cache.Rdb.Incr(l.ctx, "1_"+smsKey).Result()
	if sms == 1 {
		cache.Rdb.Set(l.ctx, smsKey, code, time.Minute*5)
		cache.Rdb.Expire(l.ctx, "1_"+smsKey, time.Minute*1)
	} else {
		return nil, errors.New("同一手机号一分钟只允许发送一次验证码")
	}
	sendSms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, errors.New("短信发送失败,请重试")
	}
	if sendSms.Code != 2 {
		return nil, errors.New(sendSms.Msg)
	}
	return &videorpc.SendSmsResponse{}, nil
}
